Home:ALL Converter>What's the difference let f:F = f` and `let f = <F>f`

What's the difference let f:F = f` and `let f = <F>f`

Ask Time:2017-01-26T02:22:34         Author:Max Koretskyi

Json Formatter

I have the following code:

interface F {
    (): string;
    a(): number;
}

function f() {
    return '3';
}

f['a'] = function () {
    return 3;
};

Then I want to assign a function to a variable. I can do it like this:

let z = <F>f; // works

or like this:

let y: F = f; // doesn't work

What's the difference?

Author:Max Koretskyi,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/41858843/whats-the-difference-let-ff-f-and-let-f-ff
T.J. Crowder :

The root issue is that f is just a function, and you're trying to use it as though it were an instance of an interface. (And I think that's fine, it's compatible with the interface, it's just a syntax thing.)\n\nThis is fine:\n\nlet z = <F>f; // works\n\n\n...because it's using a cast to tell TypeScript that although f is just a function as far as TypeScript knows, you know better and it's compatible with the interface F. Then type inference comes into play and assigns the type F to z because the right-hand side of the assignment is of type F.\n\nBut this:\n\nlet y: F = f; // doesn't work\n\n\n...doesn't work because it's declaring y as being type F, and then assigning a function to it. The function isn't of type F, so the assignment fails.",
2017-01-25T18:27:33
yy